import moment from "moment"
import { literatureDetail } from "../../../api/index"

// pages/literature/index.ts
Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false,
        type: -1,//0代表mp4、1代表mp3，2代表pdf
        detailData: {
            file: {
                path: ""
            }
        }
    },

    getType(url: string) {
        switch (url.substring(url.lastIndexOf('.') + 1)) {
            case "mp4":
                return 0;
            case "mp3":
                return 1;
            default:
                return 2
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(e: { id: string }) {
        literatureDetail(e.id).then((r: any) => {
            r = {
                ...r,
                created_at: moment(r.created_at * 1000).format("YYYY-MM-DD HH:mm:ss"),
            }
            this.setData({
                detailData: r,
                type: this.getType(r.file.path)
            });
        })
    },
    dialogClick() {
        this.setData({ show: true })
    },
    onClose() {
        this.setData({ show: false })
    },
    onDown() {
        this.setData({
            show: false
        });
        wx.showLoading({
            title: "下载中……",
            mask: true,
        });
        // 下载文献
        wx.downloadFile({
            url: this.data.detailData.file.path,
            success(res: any) {
                // 下载完成
                wx.hideLoading({
                    success() {
                        // 读取
                        wx.openDocument({
                            filePath: res.tempFilePath,
                            showMenu: true,
                            fileType: "pdf"
                        });
                    }
                });
            }
        })
    }
})